package controller;

import databaseLayer.ManagerUpdate;
import databaseLayer.MoviesLookUp;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import movieBean.HouseSchedule;
import movieBean.Movie;
import movieBean.SimplifiedMovie;
import userBean.UserIdentity;

/**
 *
 * @author Sam
 */
public class AddTimeSlot extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String topDisplayMsg = "";
        String address = "/addTimeSlot.jsp";
        
        HttpSession session = request.getSession();
        if (session.isNew() || !(((UserIdentity)session.getAttribute("userIdentity")).getUserType().equals("TicketingManager"))) {
            if (session.isNew()) {
                session.invalidate();
            }
            
            address = "index.do";
        }
        else {
            String movieName = request.getParameter("movie");
            
            if (movieName == null || movieName == "") {
                address = "Manage.do";
            }
            else {
                Date currentTime = new Date();
                SimpleDateFormat timeZoneFormatter = new SimpleDateFormat("z");
                String timeZone = timeZoneFormatter.format(currentTime);

                String initialTime = "0000/00/00 00:00:00 " + timeZone;
                String endTime = "9999/99/99 23:59:59 " + timeZone;

                Movie allThisMovie = MoviesLookUp.getMovie(movieName, initialTime, endTime);
                int thisMovieDuration = allThisMovie.getDuration();

                SimplifiedMovie thisMovieInfo = new SimplifiedMovie();
                thisMovieInfo.setName(allThisMovie.getName());
                thisMovieInfo.setDescription(allThisMovie.getDescription());
                thisMovieInfo.setDuration(allThisMovie.getDuration());
                thisMovieInfo.setThumbnailPath(allThisMovie.getThumbnailPath());
                thisMovieInfo.setTrailerPath(allThisMovie.getTrailerPath());

                String action = request.getParameter("action");
                if (action != null && action.equals("submitTS")) {
                    String startTimeStr = request.getParameter("startTime");
                    String houseNoStr = request.getParameter("houseNo");
                    String priceStr = request.getParameter("price");

                    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy'/'MM'/'dd HH:mm:ss z");

                    try {
                        Date inputtedStartTime = dateFormatter.parse(startTimeStr);
                        int houseNo = Integer.parseInt(houseNoStr);
                        int price = Integer.parseInt(priceStr);

                        GregorianCalendar tempCal = new GregorianCalendar();
                        boolean priceValid = true;
                        boolean timeConflict = false;

                        HouseSchedule thisHouseSchedule = MoviesLookUp.getHouseSchedule(houseNo);
                        int arrIndex = thisHouseSchedule.getNumberOfSlot();

                        for (int i = 0; i < thisHouseSchedule.getNumberOfSlot(); i++) {
                            Date thisMovieTime = dateFormatter.parse((thisHouseSchedule.getStartTime())[i]);

                            if (inputtedStartTime.before(thisMovieTime)) {
                                arrIndex = i;
                                break;
                            }
                        }

                        if (arrIndex > 0) {
                            Date previousSlot = dateFormatter.parse((thisHouseSchedule.getStartTime())[arrIndex - 1]);

                            tempCal.setTime(previousSlot);
                            tempCal.add(GregorianCalendar.MINUTE, (thisHouseSchedule.getDuration())[arrIndex - 1]);

                            if (inputtedStartTime.before(tempCal.getTime())) {
                                timeConflict = true;
                            }
                        }

                        if (arrIndex != thisHouseSchedule.getNumberOfSlot()) {
                            Date nextSlot = dateFormatter.parse((thisHouseSchedule.getStartTime())[arrIndex]);

                            tempCal.setTime(inputtedStartTime);
                            tempCal.add(GregorianCalendar.MINUTE, thisMovieDuration);

                            if (nextSlot.before(tempCal.getTime())) {
                                timeConflict = true;
                            }
                        }

                        if (price < 35) {
                            priceValid = false;
                        }

                        if (timeConflict) {
                            topDisplayMsg = "Time Conflict occurred! Movie Slot cannot be added!";
                        }
                        else if (!priceValid) {
                            topDisplayMsg = "No movies can have price lower than $35!";
                        }
                        else {
                            ManagerUpdate.addMovieSlot(movieName, startTimeStr, price, houseNo);

                            topDisplayMsg = "One movie slot is added successfully!";
                            session.setAttribute("topDisplayMsg", topDisplayMsg);

                            address = "Manage.do";
                        }
                    }
                    catch (ParseException ex) {
                        topDisplayMsg = "Start time is invalid!";
                    }
                    catch (NumberFormatException e) {
                        topDisplayMsg = "Price is invalid!";
                    }
                }

                request.setAttribute("topDisplayMsg", topDisplayMsg);
                request.setAttribute("thisMovieInfo", thisMovieInfo);
            }
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
